package edu.uwlax.cs.oayonlinestore.client.gui.stock;

import com.google.gwt.user.client.ui.TextArea;
import com.google.gwt.user.client.ui.TextBox;

import edu.uwlax.cs.oayonlinestore.client.OnlinestoreRService;
import edu.uwlax.cs.oayonlinestore.client.utils.DefaultAsyncCallback;
import edu.uwlax.cs.oayonlinestore.client.utils.FormTable;
import edu.uwlax.cs.oayonlinestore.client.utils.TitlePage;
import edu.uwlax.cs.oayonlinestore.vo.SubcategoryVO;

public class PageStockEditSubcategory extends TitlePage {

	TextBox t;

	TextArea ta;

	SubcategoryVO sub;

	int catID;

	int subId;

	String idsSaved;

	public String getAnchor(int i, int j) {
		return getAnchor(i + "-" + j);
	}

	private class SubcategoryForm extends FormTable {

		public SubcategoryForm() {
			super();
			addInput("Name", t = new TextBox());
			addInput("Description", ta = new TextArea());
			addButton("Save", null);
		}

		public void onButtonClicked() {

			sub.setTitle(t.getText());
			sub.setDescription(ta.getText());
			OnlinestoreRService.Util.getInstance().addEditSubcategory(sub,
					catID, getSaveHandler());

		}

		public void onDataLoad(Object data) {
		}
	}

	protected void create() {
		setTitle("Edit/Create Subcategory");
		add(new SubcategoryForm());
	}

	public String getID() {
		return "EditSubcategory";
	}

	public class CategoryAsycHandler extends DefaultAsyncCallback {

		public void onSuccess(Object o) {
			SubcategoryVO[] subs = (SubcategoryVO[]) o;
			int i = 0;
			boolean flag = false;
			while (i < subs.length && !flag) {
				if (subs[i].getId() == subId)
					flag = true;
				i++;
			}

			sub = subs[i - 1];
			t.setText(sub.getTitle());
			ta.setText(sub.getDescription());
		}
	}

	public boolean onShow(String ids) {

		idsSaved = ids;
		String[] idsSplit = ids.split("-");
		String id1 = idsSplit[0];
		String id2 = idsSplit[1];
		int catId = Integer.parseInt(id1);
		subId = Integer.parseInt(id2);
		catID = catId;
		setTitle((subId == 0) ? "Create SubCategory" : "Edit SubCategory");
		if (subId != 0) {

			OnlinestoreRService.Util.getInstance().getSubcategories(catId,
					new CategoryAsycHandler());

		} else {
			t.setText("");
			ta.setText("");
			sub = new SubcategoryVO(0, "", "");

		}

		return true;

	}

}
